package miku.firstgame.view
{
	import com.saia.starlingPunk.SP;

	import miku.firstgame.constrants.AppConstrants;
	import miku.firstgame.event.LoginEvent;
	import miku.firstgame.model.proxy.ProxyHelper;
	import miku.firstgame.net.pack.LoginRequestPack;
	import miku.firstgame.net.proxy.Connection;
	import miku.firstgame.world.LoginWorld;
	import miku.firstgame.world.RoomWorld;
	import miku.firstgame.world.TestWorld;

	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;

	public class LoginWorldMediator extends Mediator
	{
		public static const NAME:String = "loginWorldMediator";

		private var loginWorld:LoginWorld;

		public function LoginWorldMediator(viewComponent:Object = null)
		{
			super(NAME, viewComponent);
			this.loginWorld = viewComponent as LoginWorld;
		}

		override public function onRegister():void
		{
			super.onRegister();
			loginWorld.addEventListener(LoginEvent.USER_LOGIN, onUserLogin);
		}

		override public function onRemove():void
		{
			super.onRemove();
			loginWorld.removeEventListener(LoginEvent.USER_LOGIN, onUserLogin);
			this.loginWorld = null;
		}

		private function onUserLogin(e:LoginEvent):void
		{
			if (e.name.length != 0)
			{
				//TODO 直接登录
//				var loginXml:XML = <login/>;
//				loginXml.@n = e.name;
//				loginXml.@p = "";
				var pack:LoginRequestPack = new LoginRequestPack();
				pack.username = e.name;
				pack.password = "";
				ProxyHelper.send(pack);
			}
			loginWorld.button.isEnabled = false;
		}

		private function onloginSuccess():void
		{
			SP.world = new RoomWorld();
		}

		private function onLoginFail():void
		{
			loginWorld.button.isEnabled = true;
		}

		override public function handleNotification(note:INotification):void
		{
			switch (note.getName())
			{
				case AppConstrants.USER_LOGIN_SUCCUSS:
					onloginSuccess();
					break;
				case AppConstrants.USER_LOGIN_FAIL:
					onLoginFail();
					break;

			}
		}

		override public function listNotificationInterests():Array
		{
			return [
				AppConstrants.USER_LOGIN_SUCCUSS,
				AppConstrants.USER_LOGIN_FAIL


				];
		}

	}
}
